package com.uniknow.app.util;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.uniknow.app.R;
/**
 * 图片异步加载
 * @author Administrator
 */
public class AsyncImageLoader {  
   //SoftReference是内存引用，通过hashmap存储
   private HashMap<String, SoftReference<Drawable>> imageCache;  
   public AsyncImageLoader() {  
       imageCache = new HashMap<String, SoftReference<Drawable>>();  
   }  
   /**
    * 加载drawable，读取到drawable后用hashmap存起来，以图片地址为key，这样在重复加载的时候就可以直接取值了
    *  
    * @param imageUrl
    * @param imageCallback
    * @return drawable
    */  
   public Drawable loadDrawable(final String imageUrl,  
           final ImageCallback imageCallback) {  
	   //判断imageCahe是否包含imageUrl);
       if (imageCache.containsKey(imageUrl)) {  
           SoftReference<Drawable> softReference = imageCache.get(imageUrl);  
           //获取drawable
           Drawable drawable = softReference.get();  
           if (drawable != null) {  
               return drawable;  
           }  
       }  
       // 当创建一个新的Handler实例时, 它会绑定到当前线程和消息的队列中,开始分发数据
       // Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象
       // (2): 让一个动作,在不同的线程中执行.
       // 它安排消息,用以下方法
       // post(Runnable)
       // postAtTime(Runnable,long)
       // postDelayed(Runnable,long)
       // sendEmptyMessage(int)
       // sendMessage(Message);
       // sendMessageAtTime(Message,long)
       // sendMessageDelayed(Message,long)
       final Handler handler = new Handler() {  
           public void handleMessage(Message message) {  
               imageCallback.imageLoaded((Drawable) message.obj, imageUrl);  
           }  
       };  
       new Thread() {  
           @Override  
           public void run() {  
               Drawable drawable = loadImageFromUrl(imageUrl);  
               imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));   
               Message message = handler.obtainMessage(0, drawable);  
               handler.sendMessage(message);
           }  
       }.start();  
       return null;  
   }  
   public  Bitmap getHttpBitmap(String url){  
       URL myFileURL;  
       Bitmap bitmap=null;  
       try{  
           myFileURL = new URL(url);  
           //获得连接  
           HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();  
           //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制  
           conn.setConnectTimeout(6000);  
           //连接设置获得数据流  
           conn.setDoInput(true);  
           //不使用缓存  
           conn.setUseCaches(false);  
           //这句可有可无，没有影响  
           //conn.connect();  
           //得到数据流  
           InputStream is = conn.getInputStream();  
           //解析得到图片  
           bitmap = BitmapFactory.decodeStream(is);  
           //关闭数据流  
           is.close();  
       }catch(Exception e){  
           e.printStackTrace();  
       }  
       return bitmap;
   }
   /**
    * 获取图片Drawable
    * @param strUrl
    * @return drawable
    */  
   public static Drawable loadImageFromUrl(String strUrl) {  
       URL url;  
       InputStream i = null;  

       URL myFileURL;  
       Drawable d=null;  
       try{  
           myFileURL = new URL(strUrl);  
           //获得连接  
           HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();  
           //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制  
           conn.setConnectTimeout(6000);  
           //连接设置获得数据流  
           conn.setDoInput(true);  
           //不使用缓存  
           conn.setUseCaches(false);  
           //这句可有可无，没有影响  
           //conn.connect();  
           //得到数据流  
           InputStream is = conn.getInputStream();  
           //解析得到图片  
          // bitmap = BitmapFactory.decodeStream(is);  
           d = Drawable.createFromStream(is, "src"); 
           //关闭数据流  
           is.close();  
       }catch(Exception e){  
           e.printStackTrace();  
       }  
       return d;  
   }  

   public interface ImageCallback {  
       /** 这个接口用来实现回调
        * @param imageDrawable
        * @param imageUrl
        */  
       public void imageLoaded(Drawable imageDrawable, String imageUrl);  
   }
   
   /**
	 * 懒加载
    * @param image
    * @param imageURL
    * @param imageLoader
    */
	public void loadImageCanche(ImageView image,String imageURL,AsyncImageLoader imageLoader){
		final ImageView imageView = image;
		Drawable cachedImage = imageLoader.loadDrawable(imageURL, new ImageCallback() {  
	           public void imageLoaded(Drawable imageDrawable, String imageUrl) {  
	               imageView.setImageDrawable(imageDrawable);  
	           }  
	       });  
	       if (cachedImage == null) {  
	           imageView.setImageResource(R.drawable.u27);//在图片没有读取出来的情况下预先放一张图  
	       } else {  
	    	  
	           imageView.setImageDrawable(cachedImage);  
	       }
	}
	/**
	 * 显示免费标签
	 * @param free
	 * @param Price
	 */
	public void changeFree(ImageView free,String Price){
		final ImageView imageView = free;
		if(Price.equals("0.00")){
			imageView.setVisibility(0);
		}
		
	}
	/**
	 * 添加进度条
	 * @param down
	 * @param bar
	 */
	public void addProgressBar(final Button down,ProgressBar bar){
		new Thread() {  
	           @Override  
	           public void run() {  
	        	   RelativeLayout layout = (RelativeLayout) down.getParent();
	       			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,10);
	       		  params.addRule(RelativeLayout.CENTER_IN_PARENT);
	       		  if(layout.findViewById(1214)!=null)
	       				layout.removeView(layout.findViewById(1214));
	       				layout.addView(down, params);
	           }  
	       }.start();  
	}

}